package hbasecli.binary.controller;

import java.io.IOException;
import javax.annotation.Resource;

import hbasecli.binary.model.*;
import hbasecli.binary.service.HBaseServiceForBinary;
import hbasecli.exception.ParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class BinaryController {

    private static final Logger log = LoggerFactory.getLogger(BinaryController.class);

    @Resource
    private HBaseServiceForBinary service;

    @PostMapping(value = "/api/binary/row/query")
    public ResponseEntity<byte[]> query(@RequestParam("file") MultipartFile file) {
        QueryParam param;
        try {
            param = QueryParam.parseFrom(file.getBytes());
        } catch (IOException e) {
            log.error("无法正确解析参数: ", e);
            throw new ParamException("无法正确解析参数");
        }
        RowObjectsResponse rowObjectsResponse = service.query(param);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(rowObjectsResponse.toByteArray(), httpHeaders, HttpStatus.OK);
    }

    @PostMapping(value = "/api/binary/row/create")
    public ResponseEntity<byte[]> createRow(@RequestParam("file") MultipartFile file) {
        CreateRowParam param;
        try {
            param = CreateRowParam.parseFrom(file.getBytes());
        } catch (IOException e) {
            log.error("无法正确解析参数: ", e);
            throw new ParamException("无法正确解析参数");
        }
        BooleanResponse booleanResponse = service.createRow(param);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(booleanResponse.toByteArray(), httpHeaders, HttpStatus.OK);
    }

    @PostMapping(value = "/api/binary/row/delete")
    public ResponseEntity<byte[]> deleteRow(@RequestParam("file") MultipartFile file) {
        DeleteRowParam param;
        try {
            param = DeleteRowParam.parseFrom(file.getBytes());
        } catch (IOException e) {
            log.error("无法正确解析参数: ", e);
            throw new ParamException("无法正确解析参数");
        }
        BooleanResponse booleanResponse = service.deleteRow(param);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(booleanResponse.toByteArray(), httpHeaders, HttpStatus.OK);
    }

}
